package cn.itcast.shiro;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    /*
        认证安全数据
            请求参数：AuthenticationToken （获取：邮箱+密码）
            返回结果：AuthenticationInfo 安全数据
                        principal：返回的user对象
                        credentials：数据库正确的密码
                        realmName：realm名称
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证...");
        // 获取用户输入的token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 获取邮箱
        String email = token.getUsername();
        // 调用dao查询
        User user = userDao.findByEmail(email);
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    @Autowired
    private ModuleService moduleService;

    /*
        授权安全数据
            请求参数：PrincipalCollection 获取登录人信息，user对象
            返回结果：AuthorizationInfo 授权安全数据（角色、权限）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权...");
        // 1.获取user对象
        User user = (User) principalCollection.getPrimaryPrincipal();
        // 2.根据user对象查询动态模块（权限）
        List<Module> modules = moduleService.findModuleListByUser(user);
        // 3.告诉shiro框架，当前用户具有什么权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        modules.forEach(module -> {
            authorizationInfo.addStringPermission(module.getName());
        });

        System.out.println("当前登录人："+user.getUserName()+"，具有的权限："+authorizationInfo.getStringPermissions());
        return authorizationInfo;
    }

}
